#include "networkpacket.h"

NetworkPacket::NetworkPacket(unsigned short packetType, QByteArray rawData)
{
    this->packetType = packetType;
    this->body = rawData;
    this->params = new QHash<QString,QVariant>();
}

NetworkPacket* NetworkPacket::setParam(QString key, QVariant value)
{
    this->params->insert(key, value);
    return this;
}

QByteArray NetworkPacket::rawData()
{
    QByteArray s;
    if(this->params->count())
    {
        s.append("{");
        int i = 0;
        foreach(const QString &key, this->params->keys())
        {
            if(i)
            {
                s.append(",");
            }
            s.append(tr("\"%1\":\"%2\"").arg(key, this->params->value(key).toString()));
            i++;
        }
        s.append("}");
    }
    s.append(this->body);

    unsigned int packetLength = s.length();
    QByteArray packetLengthPacked;
    packetLengthPacked.append((packetLength &       0xFF));
    packetLengthPacked.append((packetLength &     0xFF00) >> 8);
    packetLengthPacked.append((packetLength &   0xFF0000) >> 16);
    packetLengthPacked.append((packetLength & 0xFF000000) >> 24);

    QByteArray packetTypePacked;
    packetTypePacked.append((unsigned char)  (this->packetType &   0xFF)       );
    packetTypePacked.append((unsigned char) ((this->packetType & 0xFF00) >> 8) );

    return packetLengthPacked + packetTypePacked + s;
}

NetworkPacket* NetworkPacket::setBody(QByteArray data)
{
    this->params->clear();
    this->body = data;
    return this;
}

QByteArray NetworkPacket::getBody()
{
    return this->body;
}

void NetworkPacket::fromRawData(QByteArray rawData)
{
}

unsigned int NetworkPacket::getPacketType()
{
    return this->packetType;
}

QVariantMap NetworkPacket::decodeJSON()
{
    QJson::Parser parser;
    return parser.parse(this->body).toMap();
}
